package com.myph.model;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import android.R.bool;
import android.R.integer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ClientSocketNew extends Thread {

    private boolean debug = true;
    public Socket sockobj;
    public PrintWriter printWriter;
    public Reader reader;

    private String request;
    private StringBuilder response;
    private Handler handler;
    private String ip, port;
    public int mode;
    private int handlerCode;

    
    
    public void run() {
        try {
            if (mode == 1) {
                CS();
            } else if (mode == 2) {
                testConnection();
            }else if(mode == 3){
            	CSSignal();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ClientSocketNew(String ip, String port, Handler prevHandler) {
        this.ip = ip;
        this.port = port;
        this.handler = prevHandler;

    }

    public void setNewRequest(String str_Send, StringBuilder str_Response) {
        this.request = new String(str_Send);
        this.response = str_Response;
        this.mode = 1;// 需要修改mode

    }
    public void setNewRequestForLongTime(String str_Send, StringBuilder str_Response) {
        this.request = new String(str_Send);
        this.response = str_Response;
        this.mode = 3;// 需要修改mode

    }
    public void testConnection() throws IOException {
        // init
        try {
            sockobj = new Socket(ip, Integer.parseInt(port));
        } catch (Exception e) {
            e.printStackTrace();
            if(sockobj != null){
            	sockobj.close();
            }
            Message msg = new Message();
            msg.what = 1002;// 测试连接失败
            handler.sendMessage(msg);
            return;
        }
        //  测试连接成功
        Message msg = new Message();
        msg.what = 1001;
        handler.sendMessage(msg);
        sockobj.close();
    }
   
    void CS() throws UnknownHostException, IOException, InterruptedException {
        try {
            sockobj = new Socket(ip, Integer.parseInt(port));
//            sockobj.setSoTimeout(5 * 1000);
        } catch (Exception e) {
        	if(sockobj != null){
            	sockobj.close();
            }
        	Message msg = new Message();
            msg.what = 1002;// 测试连接失败
            handler.sendMessage(msg);
            e.printStackTrace();
            return;
        }
        int socketTimeout = 5*1000;
		sockobj.setSoTimeout(socketTimeout);
        
        reader = new InputStreamReader(sockobj.getInputStream());
        printWriter = new PrintWriter(sockobj.getOutputStream());

        if(debug){
            Log.d("request","request:"+request);
        }
        printWriter.print(request);
        printWriter.flush();

        handlerCode = 1003;//默认成功
        char cb[] = new char[1024*2];
        try {
            int readlen = reader.read(cb);
            StringBuffer sb = new StringBuffer();
            sb.append(new String(cb, 0, readlen));
            
            response.delete(0, response.length());
            
            if(!sb.toString().isEmpty()){
                response.append(sb.toString());//未超时,但操作可能失败
            }
            reader.close();
            printWriter.close();
           
        } catch (SocketTimeoutException e1) {
            Log.d("", "timeout");
            handlerCode = 1004;// 超时情况
        } finally {
            // 
        	if(reader != null){
        		reader.close();
        	}
        	if(printWriter != null){
        		printWriter.close();
        	}
        	if(sockobj != null){
            	sockobj.close();
            }
            Log.d("csn",String.valueOf(handlerCode)+",csn_response:" + response);
            Message msg = new Message();
            msg.what = handlerCode;
            handler.sendMessage(msg);

        }

    }
    void CSSignal()throws UnknownHostException, IOException, InterruptedException {
        try {
            sockobj = new Socket(ip, Integer.parseInt(port));

        } catch (Exception e) {
        	if(sockobj != null){
            	sockobj.close();
            }
        	Message msg = new Message();
            msg.what = 1002;// 测试连接失败
            handler.sendMessage(msg);
            e.printStackTrace();
            return;
        }
        int socketTimeout = 6*1000;//让read阻塞的时间,MCU每2s发一次
		sockobj.setSoTimeout(socketTimeout);
        
        reader = new InputStreamReader(sockobj.getInputStream());
        printWriter = new PrintWriter(sockobj.getOutputStream());

        if(debug){
            Log.d("request","request:"+request);
        }
        printWriter.print(request);
        printWriter.flush();

        handlerCode = 1003;//默认成功
        char cb[] = new char[1024*2];
        try {
        	int readlen = 0;
        	while((readlen = reader.read(cb)) != 0){

	            StringBuffer sb = new StringBuffer();
	            sb.append(new String(cb, 0, readlen));
	            
	            response.delete(0, response.length());
	            
	            if(!sb.toString().isEmpty()){
	                response.append(sb.toString());//未超时,但操作可能失败
	            }
	            Log.d("csn",String.valueOf(handlerCode)+",csn_response:" + response);
	            handlerCode = 1003;
	            Message msg = new Message();
	            msg.what = handlerCode;
	            handler.sendMessage(msg);
        	}
        	if(reader != null){
        		reader.close();
        		reader = null;
        	}
        	if(printWriter != null){
        		printWriter.close();
        		printWriter = null;
        	}
           
        } catch (SocketTimeoutException e1) {
            Log.d(Util.TAG, "timeout");
            handlerCode = 1005;// 此处超时情况  仅表示数据已经正常,没有 '$danger#'警报了
        } finally {
            // 
        	if(reader != null){
        		reader.close();
        		reader = null;
        	}
        	if(printWriter != null){
        		printWriter.close();
        		printWriter = null;
        	}
        	if(sockobj != null){
            	sockobj.close();
            	sockobj = null;
            }
        	Message msg = new Message();
            msg.what = handlerCode;
            handler.sendMessage(msg);

        }

    }
    public void setTestConnectionMode() {
        this.mode = 2;
    }
}
